package com.ndood.core.render.impl;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ndood.core.proxy.UserAgentGenerator;
import com.ndood.core.render.SeleniumDriverPool;
import com.ndood.core.util.PropertiesUtil;

/**
 * Phantomjs WebDriver队列（池）
 */
public class PhantomJsDriverPool implements SeleniumDriverPool {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 最大webDriver数量
	 */
	private int CAPACITY = 30;

	/**
	 * 当前webDriver数量
	 */
	private AtomicInteger refCount = new AtomicInteger(0);

	/**
	 * 内存阻塞队列
	 */
	private BlockingDeque<WebDriver> driverQueue = new LinkedBlockingDeque<WebDriver>(CAPACITY);

	public PhantomJsDriverPool() {
		super();
	}

	public PhantomJsDriverPool(int poolsize) {
		this.CAPACITY = poolsize;
		driverQueue = new LinkedBlockingDeque<WebDriver>(poolsize);
	}

	/**
	 * 从队列中取出一个webDriver
	 */
	public WebDriver get() throws InterruptedException {
		// Step1: 如果webDriver数量已最大，则从队列中取
		if (refCount.get() >= CAPACITY) {
			return driverQueue.take();
		}

		// Step2: 初始化phantomjs浏览器属性
		DesiredCapabilities caps = DesiredCapabilities.phantomjs();
		caps.setJavascriptEnabled(true);
		caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
				PropertiesUtil.readProperty("phantomjs.path"));
		caps.setCapability("takesScreenshot", true);
		caps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent",
				UserAgentGenerator.generate());
		caps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_CUSTOMHEADERS_PREFIX + "User-Agent",
				UserAgentGenerator.generate());
		
		// Step3: 配置代理
		/*caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] { "--ignore-ssl-errors=yes",
				"--disk-cache=true", "--ssl-protocol=any", "--proxy=" + DynamicIpPortGenerator.generate() });*/
		
		// Step4: 如果webDriver数量未达到最大，则新增一个
		WebDriver webDriver = new PhantomJSDriver(caps);
		webDriver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
		webDriver.manage().window().setSize(new Dimension(1366, 768));
		refCount.incrementAndGet();
		driverQueue.put(webDriver);

		// Step5: 先放入队列中然后再取
		webDriver = driverQueue.take();
		return webDriver;
	}

	/**
	 * 用完之后返回一个webDriver到队列中
	 */
	public void returnToPool(WebDriver webDriver) {
		try {
			driverQueue.put(webDriver);
		} catch (InterruptedException e) {
			logger.warn("returnToPool InterruptedException", e);
		}
	}

	/**
	 * 关闭webDriver队列
	 */
	public void shutdown() {
		try {
			for (WebDriver driver : driverQueue) {
				refCount.decrementAndGet();
				driver.close();
				driver.quit();
				driver = null;
			}
			driverQueue.clear();
		} catch (Exception e) {
			logger.warn("webdriverpool关闭失败", e);
		}
	}
}
